#include "sourcetree.h"
#include "../dokermodel.h"

#include <QtCore/qdebug.h>
#include <QtGui/qevent.h>
#include <QtGui/qheaderview.h>
#include <QtGui/qicon.h>

SourceTree::SourceTree(DokerModel *model, QWidget *parent) :
    QTreeWidget(parent)
{
    m_model = model;
    header()->hide();
    connect(m_model, SIGNAL(fileAdded(QString,QString)), this, SLOT(addItem(QString,QString)));
    connect(m_model, SIGNAL(modified(QString,bool)), this, SLOT(update(QString,bool)));
}

void SourceTree::addItem(const QString &groupName, const QString &itemName)
{
    SourceItem *groupItem = findGroupItem(groupName);
    if (!groupItem)
    {
        groupItem = new SourceItem(this, groupName, SourceItem::GroupType);
        groupItem->setIcon(0, QIcon(":/images/dokz.png"));
        addTopLevelItem(groupItem);
        groupItem->setExpanded(true);
    }
    SourceItem *newItem = new SourceItem(groupItem, itemName, SourceItem::FileType);
    if (itemName.endsWith("main.doks", Qt::CaseInsensitive))
        newItem->setIcon(0, QIcon(":/images/script_main.png"));
    else if (itemName.endsWith(".doks", Qt::CaseInsensitive))
        newItem->setIcon(0, QIcon(":/images/script.png"));
    groupItem->addChild(newItem);
}

SourceItem *SourceTree::findFileItem(const QString &fileName)
{
    SourceItem *fileItem = 0;
    for (int i = 0; (i < topLevelItemCount()) && !fileItem; ++i)
    {
        SourceItem *parentItem = static_cast<SourceItem*>(topLevelItem(i));
        for (int j = 0; (j < parentItem->childCount()) && !fileItem; ++j)
        {
            SourceItem *childItem = static_cast<SourceItem*>(parentItem->child(j));
            if (childItem->isFile() && childItem->fileName() == fileName)
                fileItem = childItem;
        }
    }
    return fileItem;
}

SourceItem *SourceTree::findGroupItem(const QString &fileName)
{
    SourceItem *groupItem = 0;
    for (int i = 0; (i < topLevelItemCount()) && !groupItem; ++i)
    {
        SourceItem *item = static_cast<SourceItem*>(topLevelItem(i));
        if (item->isGroup() && item->fileName() == fileName)
            groupItem = item;
    }
    return groupItem;
}

void SourceTree::mouseDoubleClickEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        SourceItem *item = static_cast<SourceItem*>(currentItem());
        if (item && item->isFile())
        {
            m_model->editRequest(item->fileName());
            event->accept();
        }
    }
    QTreeWidget::mouseDoubleClickEvent(event);
}

void SourceTree::update(const QString &fileName, bool modified)
{
    SourceItem *fileItem = findFileItem(fileName);
    if (fileItem)
        fileItem->setText(0, fileName + (modified ? "*" : ""));
}
